#include "app_mqtt.h"

static MQTTClient_message pubmsg = MQTTClient_message_initializer;
static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static int (*mqtt_recieve_callback)(char *) = NULL;

void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("消息发送成功");
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    if (mqtt_recieve_callback)
    {
        if (mqtt_recieve_callback((char *)message->payload) != 0)
        {
            log_error("消息接收失败");
            return 0;
        }
    }
    log_debug("收到消息: %s", message->payload);
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

void connlost(void *context, char *cause)
{
    log_error("连接丢失: %s", cause);
}

int app_mqtt_init(void)
{
    // 创建MQTT客户端
    if (MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端创建失败");
        return -1;
    }
    log_info("MQTT客户端已创建");
    // 设置MQTT客户端的回调函数
    if (MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端设置回调函数失败");
        MQTTClient_destroy(&client);
        return -1;
    }
    log_info("MQTT客户端已设置回调函数");
    // 连接到MQTT服务器
    if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端连接失败");
        MQTTClient_destroy(&client);
        return -1;
    }
    log_info("MQTT客户端已连接");
    // 订阅主题
    if (MQTTClient_subscribe(client, TOPIC_RTG, QOS) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端订阅主题失败");
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }
    log_info("MQTT客户端已订阅主题");
    return 0;
}
int app_mqtt_send(char *json)
{
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    pubmsg.qos = QOS;
    if (MQTTClient_publishMessage(client, TOPIC_GTR, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTT客户端发送消息失败");
        return -1;
    }
    
    return 0;
}
void app_mqtt_close(void)
{
    MQTTClient_unsubscribe(client, TOPIC_RTG);
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
    log_info("MQTT客户端已关闭");
}
void app_mqtt_registerRecvCallback(int (*callback)(char *))
{
    mqtt_recieve_callback = callback;
}
